<template>
	<view class="container">
		<page-layout title="标签管理" button-text="添加新标签" content-bg-color="#FFFFFF" button-wrapper-bg-color="#EFEFEF" @back="handleBack" @button-click="handleAddTag">
			<!-- 标签列表 -->
			<view class="tags-list">
					<view 
						class="tag-item" 
						v-for="(tag, index) in tags" 
						:key="tag.id"
						:style="getDragStyle(index)"
					>
						<view class="tag-name" @click="handleTagClick(tag)">{{ tag.name }}</view>
						<view 
							class="sort-icon"
							@touchstart.stop="handleDragStart($event, index)"
							@touchmove.stop="handleDragMove($event, index)"
							@touchend.stop="handleDragEnd($event, index)"
						>
							<view class="sort-line"></view>
							<view class="sort-line"></view>
							<view class="sort-line"></view>
						</view>
					</view>
				</view>
		</page-layout>

		<!-- 添加/修改标签弹窗 -->
		<add-tag-modal 
			:visible="showAddTagModal" 
			:edit-mode="isEditMode"
			:initial-value="selectedTag ? selectedTag.name : ''"
			@close="closeAddTagModal"
			@save="handleSaveTag"
		/>

		<!-- 标签操作弹窗 -->
		<tag-action-modal 
			:visible="showTagActionModal"
			:tag-name="selectedTag ? selectedTag.name : ''"
			@close="closeTagActionModal"
			@modify="handleModifyTag"
			@delete="handleDeleteTag"
		/>

		<!-- 删除确认弹窗 -->
		<delete-tag-confirm-modal 
			:visible="showDeleteConfirmModal"
			@close="closeDeleteConfirmModal"
			@confirm="confirmDeleteTag"
		/>
	</view>
</template>

<script>
	import { getAllTags, addTag, updateTag, deleteTag, updateTagOrder, initDefaultTags } from '@/utils/tagService.js';
	
	export default {
		data() {
			return {
				tags: [],
				draggingIndex: -1,
				dragStartY: 0,
				dragOffsetY: 0,
				dragOverIndex: -1,
				showAddTagModal: false,
				showTagActionModal: false,
				showDeleteConfirmModal: false,
				selectedTag: null,
				isEditMode: false
			}
		},
		onLoad() {
			// 初始化默认标签（如果存储为空）
			initDefaultTags();
			// 加载标签列表
			this.loadTags();
		},
		methods: {
			loadTags() {
				this.tags = getAllTags();
			},
			handleBack() {
				uni.navigateBack();
			},
			handleDragStart(e, index) {
				// 开始拖动
				this.draggingIndex = index;
				this.dragStartY = e.touches[0].clientY;
				this.dragOffsetY = 0;
				this.dragOverIndex = -1;
			},
			handleDragMove(e, index) {
				if (this.draggingIndex !== index) return;
				
				// 计算移动距离
				const currentY = e.touches[0].clientY;
				this.dragOffsetY = currentY - this.dragStartY;
				
				// 根据移动距离计算目标位置
				const itemHeight = 100;
				const moveOffset = Math.round(this.dragOffsetY / itemHeight);
				const newIndex = Math.max(0, Math.min(this.tags.length - 1, index + moveOffset));
				
				// 设置目标位置
				if (newIndex !== index) {
					this.dragOverIndex = newIndex;
				} else {
					this.dragOverIndex = -1;
				}
			},
			getDragStyle(index) {
				if (this.draggingIndex === -1) {
					return {};
				}
				
				// 被拖动的项目跟随手指移动
				if (this.draggingIndex === index) {
					return {
						transform: `translateY(${this.dragOffsetY}px)`,
						opacity: 0.8,
						zIndex: 1000
					};
				}
				
				// 计算其他项目需要移动的距离
				const itemHeight = 100;
				let translateY = 0;
				
				if (this.dragOverIndex !== -1 && this.dragOverIndex !== this.draggingIndex) {
					const draggingFrom = this.draggingIndex;
					const draggingTo = this.dragOverIndex;
					
					// 向下拖动
					if (draggingTo > draggingFrom) {
						// 在拖动项目和目标位置之间的项目向上移动
						if (index > draggingFrom && index <= draggingTo) {
							translateY = -itemHeight;
						}
					} 
					// 向上拖动
					else if (draggingTo < draggingFrom) {
						// 在目标位置和拖动项目之间的项目向下移动
						if (index >= draggingTo && index < draggingFrom) {
							translateY = itemHeight;
						}
					}
				}
				
				if (translateY !== 0) {
					return {
						transform: `translateY(${translateY}px)`,
						transition: 'transform 0.2s ease-out'
					};
				}
				
				return {};
			},
			handleDragEnd(e, index) {
				if (this.draggingIndex !== index) return;
				
				// 如果有有效的目标位置，则交换
				if (this.dragOverIndex >= 0 && this.dragOverIndex < this.tags.length && this.dragOverIndex !== index) {
					// 交换数组中的元素
					const tags = [...this.tags];
					const [removed] = tags.splice(index, 1);
					tags.splice(this.dragOverIndex, 0, removed);
					this.tags = tags;
					
					// 保存新的顺序到存储
					const tagIds = tags.map(tag => tag.id);
					updateTagOrder(tagIds);
				}
				
				// 重置拖拽状态
				this.draggingIndex = -1;
				this.dragStartY = 0;
				this.dragOffsetY = 0;
				this.dragOverIndex = -1;
			},
			handleAddTag() {
				// 打开添加标签弹窗
				this.isEditMode = false;
				this.selectedTag = null;
				this.showAddTagModal = true;
			},
			closeAddTagModal() {
				this.showAddTagModal = false;
				// 关闭弹窗时，如果不是编辑模式，清空选中标签
				// 编辑模式下如果用户取消，也需要重置状态
				if (!this.isEditMode) {
					this.selectedTag = null;
				} else {
					// 用户取消了编辑，重置状态
					this.isEditMode = false;
					// selectedTag 保留，因为可能用户还想再次操作这个标签
				}
			},
			handleSaveTag(tagName) {
				try {
					if (this.isEditMode && this.selectedTag) {
						// 修改标签名称
						updateTag(this.selectedTag.id, tagName);
						// uni.showToast({
						// 	title: '修改成功',
						// 	icon: 'success'
						// });
						this.loadTags(); // 重新加载标签列表
						this.closeAddTagModal();
						// 修改成功后，清空 selectedTag 和编辑模式
						this.selectedTag = null;
						this.isEditMode = false;
					} else {
						// 添加新标签
						addTag(tagName);
						// uni.showToast({
						// 	title: '添加成功',
						// 	icon: 'success'
						// });
						this.loadTags(); // 重新加载标签列表
						this.closeAddTagModal();
					}
				} catch (error) {
<<<<<<< HEAD
					// uni.showToast({
					// 	title: error.message || '操作失败',
					// 	icon: 'none'
					// });
=======
					uni.showToast({
						title: error.message || '操作失败',
						icon: 'none'
					});
>>>>>>> 41bd8f60563759fef0935294134d79a92fb57c16
				}
			},
			handleTagClick(tag) {
				// 点击标签名称，打开操作弹窗
				this.selectedTag = tag;
				this.showTagActionModal = true;
			},
			closeTagActionModal() {
				this.showTagActionModal = false;
				this.selectedTag = null;
			},
			handleModifyTag() {
				// 关闭操作弹窗，打开修改弹窗
				// 注意：不要清空 selectedTag，因为保存时需要用到
				this.isEditMode = true;
				this.showTagActionModal = false;
				this.showAddTagModal = true;
			},
			handleDeleteTag() {
				// 打开删除确认弹窗
				if (!this.selectedTag) return;
				this.showTagActionModal = false;
				this.showDeleteConfirmModal = true;
			},
			closeDeleteConfirmModal() {
				this.showDeleteConfirmModal = false;
			},
			confirmDeleteTag() {
				// 确认删除标签
				if (!this.selectedTag) return;
				
				try {
					const success = deleteTag(this.selectedTag.id);
					if (success) {
						// uni.showToast({
						// 	title: '删除成功',
						// 	icon: 'success'
						// });
						this.loadTags(); // 重新加载标签列表
					} else {
						// uni.showToast({
						// 	title: '删除失败',
						// 	icon: 'none'
						// });
					}
				} catch (error) {
<<<<<<< HEAD
					// uni.showToast({
					// 	title: error.message || '删除失败',
					// 	icon: 'none'
					// });
=======
					uni.showToast({
						title: error.message || '删除失败',
						icon: 'none'
					});
>>>>>>> 41bd8f60563759fef0935294134d79a92fb57c16
				}
				
				this.closeDeleteConfirmModal();
				this.closeTagActionModal();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: 100vh;
		position: relative;
	}

	.tags-list {
		flex: 1;
		background-color: #FFFFFF;
	}

	.tag-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 32rpx;
		transition: transform 0.1s ease-out;
		position: relative;
	}

	.tag-name {
		font-size: 30rpx;
		color: #333333;
		flex: 1;
		letter-spacing: 0.3rpx;
		font-family: 'SimHei', '黑体', sans-serif;
	}

	.sort-icon {
		display: flex;
		flex-direction: column;
		gap: 6rpx;
		align-items: center;
		justify-content: center;
		width: 48rpx;
		height: 48rpx;
		padding: 8rpx;
		touch-action: none;
		user-select: none;
		cursor: grab;
		
		&:active {
			cursor: grabbing;
		}
	}

	.sort-line {
		width: 36rpx;
		height: 2rpx;
		background-color: #CCCCCC;
		border-radius: 1rpx;
	}
</style>

